package com.hfdg.prototype.base.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName CamelUtils
 * @Description TODO
 * @Author yuelh
 * @Date 2018/12/3 18:40
 * @Version 1.0
 * @Company 会飞的锅工作室
 **/
public class CamelUtils {
    private static final Pattern underline2Camel=Pattern.compile("([A-Za-z\\d]+)(_)?");
    private static final Pattern  camel2Underline = Pattern.compile("[A-Z]([a-z\\d]+)?");
    /**
     * 下划线转驼峰法(默认小驼峰)
     *
     * @param line       源字符串
     * @param smallCamel 大小驼峰,是否为小驼峰(驼峰，第一个字符是大写还是小写)
     * @return 转换后的字符串
     */
    public static String underline2Camel(String line, boolean... smallCamel) {
        if (line == null || "".equals(line)) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Matcher matcher = underline2Camel.matcher(line);
        //匹配正则表达式
        while (matcher.find()) {
            String word = matcher.group();
            //当是true 或则是空的情况
            if ((smallCamel.length == 0 || smallCamel[0]) && matcher.start() == 0) {
                sb.append(Character.toLowerCase(word.charAt(0)));
            } else {
                sb.append(Character.toUpperCase(word.charAt(0)));
            }
            int index = word.lastIndexOf('_');
            if (index > 0) {
                sb.append(word.substring(1, index).toLowerCase());
            } else {
                sb.append(word.substring(1).toLowerCase());
            }
        }
        return sb.toString();
    }
    /**
     * 驼峰法转下划线
     * @param camelStr 源字符串,驼峰字符砖
     * @return 转换后的字符串
     */
    public static String camel2Underline(String camelStr) {
        if (camelStr == null || "".equals(camelStr)) {
            return "";
        }
        camelStr = String.valueOf(camelStr.charAt(0)).toUpperCase().concat(camelStr.substring(1));
        StringBuffer sb = new StringBuffer();
        Matcher matcher = camel2Underline.matcher(camelStr);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == camelStr.length() ? "" : "_");
        }
        return sb.toString().toLowerCase();
    }
}
